package com.lili.backtrack;

import java.util.*;

/**
 * @Auther: 李 力
 * @Date: 2024/8/21
 * @Description: 四数之和:也是通用的n数之后
 * @version: 1.0
 */
public class LeetCode18 {
    public static List<List<Integer>> fourSum(int[] nums, int target) {
        List<List<Integer>> result = new ArrayList<>();
        Arrays.sort(nums);
        dfs(4, 0, nums.length - 1, 0, nums, new LinkedList<>(), result);
        return result;
    }

    private static void dfs(int n, int i, int j, int target, int[] nums, LinkedList<Integer> stack,
                            List<List<Integer>> result
    ) {
        if (n == 2) {
            //两数之和,不用递归
            two(i, j, nums, target, stack, result);
            return;
        }
        for (int k = i; k < j - (n - 2); k++) {
            if (k > i && nums[k] == nums[k] - 1) {
                continue;
            }
            stack.push(nums[k]);
            dfs(n - 1, k + 1, j, target - nums[k], nums, stack, result);
            stack.pop();
        }
    }

    private static void two(int i, int j, int[] nums, int target,
                            LinkedList<Integer> stack,
                            List<List<Integer>> result) {
        while (i < j) {
            int sum = nums[i] + nums[j];
            if (sum > target) {
                i++;
            } else if (sum < target) {
                j--;
            } else {
                ArrayList<Integer> list = new ArrayList<>(stack);
                list.add(nums[i]);
                list.add(nums[j]);
                result.add(list);
                //继续查找其他解
                i++;
                j--;
                while (i < j && nums[i] == nums[i - 1]) {
                    i++;
                }
                while (i < j && nums[j] == nums[j + 1]) {
                    j--;
                }
            }
        }
    }

}
